layui.use(['form','layer','layedit','laydate','upload','flow'],function(){
    var form = layui.form
    layer = parent.layer === undefined ? layui.layer : top.layer,
        laypage = layui.laypage,
        upload = layui.upload,
        layedit = layui.layedit,
        laydate = layui.laydate,
        flow = layui.flow,
        $ = layui.jquery;

    //用于同步编辑器内容到textarea
    layedit.sync(editIndex);

    var goodsImgList = [];

    //上传缩略图
    upload.render({
        elem: '.thumbBox',
        url: '/file/save',
        method : "post",  //此处是为了演示之用，实际使用中请将此删除，默认用post方式提交
        done: function(res, index, upload){
            var fileId = res.data.fileId;
            var url = "/file/get/" + fileId;
            $('.thumbImg').attr('src',url);
            $('.thumbBox').css("background","#fff");
            //文件URL
            $('input[name="picUrl"]').val(url);
        }
    });

    //创建一个编辑器
    var editIndex = layedit.build('goods_content',{
        height : 535,
        uploadImage : {
            url : "/file/save",
            type:'post'
        }
    });

    form.on("submit(add_goods)",function(data){
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        $.post("/saveGoods",{
            id:$("input[name=id]").val(),
            picUrl:$("input[name=picUrl]").val(),
            name:$(".name").val(),
            categoryId:$(".categoryId").val(),
            miniPrice:$(".miniPrice").val(),
            originalPrice:$(".originalPrice").val(),
            logisticsId:$(".logisticsId").val(),
            displayOrder:$(".displayOrder").val(),
            stores:$(".stores").val(),
            weight:$(".weight").val(),
            status:$(".status").val(),
            content:layedit.getContent(editIndex).split('<audio controls="controls" style="display: none;"></audio>')[0],
            picUrls:JSON.stringify(goodsImgList)
        },function(res){
            top.layer.close(index);
            top.layer.msg("商品添加成功！");
            layer.closeAll("iframe");
            //刷新父页面
            parent.location.reload();
        });
        return false;
    });

    //初始化下拉选项（最好是最后来初始化）
    function initSelect(){
        $('select').each(function(index,element){
            var url = $(element).attr("data-url");
            var page = $(element).attr("data-page");
            var key = $(element).attr("data-key");
            var value = $(element).attr("data-value");
            url = url ? url : "/getDictByPageKey";
            $.get(url,{page:page,key:key}, function(result){
                if(result.msg === 'success'){
                    var items = result.data;
                    items.forEach(function(item){
                        $(element).append("<option value='" + item.value + "'>"+ item.name + "</option>")
                    });
                    if(value){
                        $(element).val(value);
                    }
                    form.render("select");
                }
            });
        });
    }
    //最后初始化下拉选项
    initSelect();

    //流加载图片
    flow.load({
        elem: '#Images', //流加载容器
        done: function(page, next){ //加载下一页
            $.get("/findPicByGoodsId",
                {goodsId:$("input[name=id]").val()},
                function(res){
                    //模拟插入
                    var imgList = [],data= res.data;
                    goodsImgList = data;
                    for(var i=0; i<data.length; i++){
                        imgList.push('<li><img layer-src="'+ data[i].picUrl +'" src="../../'+ data[i].picUrl +'"><div class="operate"><i class="layui-icon img_del">&#xe640;</i></div></li>');
                    }
                    next(imgList.join(''), false);
                    form.render();
            });
        }
    });

    //设置图片的高度
    $(window).resize(function(){
        $("#Images li img").height($("#Images li img").width());
    });

    //多图片上传
    upload.render({
        elem: '.uploadGoodsBannerImg',
        url: '/file/save',
        multiple: false,
        done: function(res){
            var data = res.data;
            $('#Images').prepend('<li><img layer-src="'+ data.src +'" src="'+ data.src +'" class="layui-upload-img"><div class="operate"><i class="layui-icon img_del">&#xe640;</i></div></li>')
            //设置图片的高度
            $("#Images li img").height($("#Images li img").width());

            goodsImgList.push({picUrl:data.src})
        }
    });
    //弹出层
    $("body").on("click","#Images img",function(){
        top.showImg();
    });
    //删除单张图片
    $("body").on("click",".img_del",function(){
        var _this = $(this);
        layer.confirm('确定删除该图片吗？',{icon:3, title:'提示信息'},function(index){
            var picUrl = _this.parents("li").find("img").attr("layer-src");

            _this.parents("li").hide(1000);
            setTimeout(function(){_this.parents("li").remove();},950);

            goodsImgList = goodsImgList.filter(function (item) {
                return item.picUrl !== picUrl;
            });

            layer.close(index);
        });
    })
});